package cn.may.controller;

import cn.may.easyexcel.EasyExcelUtil;
import cn.may.easyexcel.PhoneDataListener;
import cn.may.easyexcel.UserDataListener;
import cn.may.easypoi.WordUtil;
import cn.may.entity.Phone;
import cn.may.entity.Student;
import cn.may.excel.ExcelUtil;
import cn.may.exception.BusinessException;
import cn.may.mybatisplus.service.StudentService;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author mayuanbao
 * @date 2019-08-21 21:17
 */
@RestController
public class HelloWorld {
    @Value("${utils.msg}")
    private String msg;
    @Resource
    StudentService studentService;

    @RequestMapping("/hello")
    public String index() {
//        int no = 1/0;
        System.out.println(msg);
        throw new BusinessException("100", "用户名密码错误！");
    }

    @PostMapping("/readExcel")
    public void readExcel(MultipartFile file) throws IOException {
        List<List<List<String>>> list = ExcelUtil.readExcel(file, 1);
        System.out.println(list.get(0));
        System.out.println("-----------------------");
        System.out.println(list.get(0).get(0));
        System.out.println("-----------------------");
        System.out.println(list.get(0).get(0).get(0));
        List<String> sheetNames = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            sheetNames.add(String.valueOf(i));
        }
        ExcelUtil.writeExcel03(list, sheetNames);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/readExcel01")
    public void multiRead(MultipartFile file) throws IOException {

//        String fileName = "src/main/resources/demo.xlsx";
        List<Class<?>> clzz = new ArrayList<>();
        clzz.add(Student.class);
        clzz.add(Phone.class);
        List<AnalysisEventListener<?>> listeners = new ArrayList<>();
        listeners.add(new UserDataListener(studentService));
        listeners.add(new PhoneDataListener());
        long start = System.currentTimeMillis();
        EasyExcelUtil.multiRead(file.getInputStream(), clzz, listeners);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/download02")
    public String download(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName =
                    URLEncoder
                            .encode("测试", "UTF-8")
                            .replaceAll("\\+", "%20") + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            List<List<?>> lists = new ArrayList<>();
            List<Student> students = studentService.list();
            lists.add(students);
            // 这里需要设置不关闭流
            EasyExcelUtil.multiWrite(response.getOutputStream(), Collections.singletonList("student"),
                    Collections.singletonList(Student.class), lists);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(1);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
        return "success";
    }

    @GetMapping("/export2Word")
    public String export2Word(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName =
                URLEncoder
                        .encode("demo", "UTF-8")
                        .replaceAll("\\+", "%20") + System.currentTimeMillis() + ".docx";
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        Map<String, Object> map = new HashMap<>(1);
        map.put("name", "张三");
        map.put("date", "2020-02-02");
        map.put("startDate", "2020-02-05");
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "demo.docx";
        System.out.println(filePath);
        return WordUtil.simpleWordExport(filePath, response.getOutputStream(), map);
    }

}
